package plus.xj17520.org.service.impl;

import plus.xj17520.basic.domain.BaseQuery;
import plus.xj17520.basic.util.PageList;
import plus.xj17520.basic.util.TreeUtil;
import plus.xj17520.org.domain.Department;
import plus.xj17520.org.domain.Employee;
import plus.xj17520.org.mapper.DepartmentMapper;
import plus.xj17520.org.mapper.EmployeeMapper;
import plus.xj17520.org.service.IDepartmentService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional //默认就是强制事务
public class DepartmentServiceImpl implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;
    @Autowired
    private EmployeeMapper employeeMapper;




    @Override
    @Transactional(readOnly = true)
    public Department loadById(Long id) {
        return departmentMapper.loadById(id);
    }

    @Override
    public void save(Department department) {

        department.init();
        //第一次保存时 insert into  ****
        departmentMapper.save(department);
        //第二次执行,使用的是同一个sqlsession
        //departmentMapper.save(department);
    }


    @Override
    public void update(Department department) {
        departmentMapper.update(department);
    }

    @Override
    public void remove(Long id) {
        departmentMapper.remove(id);
    }

    @Override
    public  PageList<Department>  queryData(BaseQuery query) {
        //1.创建分页对象
        PageHelper.startPage(query.getPage(), query.getPageSize());
        //2.第二步:查询所有
        List<Department> departments = departmentMapper.loadAll(query);
        //3.创建分页对象 为什么需要用PageInfo接收
        PageInfo<Department> pageInfo = new PageInfo<>(departments);
        //已经分页后的数据
        List<Department> depts = pageInfo.getList();
        //1.查出对应的部门经理 employee
        depts.forEach(department -> {
                //这里拿到的是员工id
                Long employeeId = department.getManagerId();
                //通过员工id查出对应的员工信息
                Employee mapperOne = employeeMapper.findOne(employeeId);
                department.setManager(mapperOne);
                //2.查出上级部门
                Department parent = departmentMapper.loadById(department.getParentId());
                department.setParent(parent);
                }
        );

        return new PageList(pageInfo.getTotal(), pageInfo.getList());
    }

    /**
     * 返回树形结构集合
     * @return
     */
    @Override
    public List<Department> findTree() {
        //第一次查询 ,它走数据库,将数据存到内存,并且返回 key : 当前的sql语句,value是当前的数据
        List<Department> tree = departmentMapper.findTree();
        departmentMapper.findTree();
        return TreeUtil.getTree(tree);
    }

    @Override
    public void batchDelete(List<Long> ids) {
        departmentMapper.batchDelete(ids);
    }
}